module Kuztuscms
  class UsersController < KuztuscmsController
    before_filter :authenticate_for_cms!, :except => [:new, :create]

    # GET /users
    def index
      @users = User.all
    end

    # GET /users/1
    def show
      @user = User.find(params[:id])
    end

    # GET /users/new
    def new
      check_first_user
      @user = User.new
    end

    # GET /users/1/edit
    def edit
      @user = User.find(params[:id])
    end

    # POST /users
    def create
      check_first_user
      @user = User.new(params[:user])

      if @user.save
        if @first_user
          sign_in @user
          Settings.set 'devise-mailer-sender', @user.email
          redirect_to root_url
        else
          redirect_to @user, notice: 'User was successfully created.'
        end
      else
        render action: "new"
      end
    end

    # PUT /users/1
    def update
      @user = User.find(params[:id])

      if @user.update_attributes(params[:user])
        redirect_to @user, notice: 'User was successfully updated.'
      else
        render action: "edit"
      end
    end

    # DELETE /users/1
    def destroy
      @user = User.find(params[:id])
      @user.destroy

      redirect_to kuztuscms.users_url
    end

    private

      def check_first_user
        if User.count > 0
          authenticate_user!
          @first_user = false
        else
          @first_user = true
        end
      end
  end
end
